package demo.spring.restful.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.stereotype.Component;

import demo.spring.restful.domain.Computer;

@Component
public class ComputerService {
	private static final AtomicLong counter = new AtomicLong();
    
    private static List<Computer> computers;
     
    static{
        computers= populateDummyComputers();
    }
 
    public List<Computer> findAllComputers() {
        return computers;
    }
     
    public Computer findById(long id) {
        for(Computer computer : computers){
            if(computer.getId() == id){
                return computer;
            }
        }
        return null;
    }
     
    public Computer findByName(String name) {
        for(Computer computer : computers){
            if(computer.getName().equalsIgnoreCase(name)){
                return computer;
            }
        }
        return null;
    }
     
    public void saveComputer(Computer computer) {
        computer.setId(counter.incrementAndGet());
        computers.add(computer);
    }
 
    public void updateComputer(Computer computer) {
        int index = computers.indexOf(computer);
        computers.set(index, computer);
    }
 
    public void deleteComputerById(long id) {
         
        for (Iterator<Computer> iterator = computers.iterator(); iterator.hasNext(); ) {
        	Computer computer = iterator.next();
            if (computer.getId() == id) {
                iterator.remove();
            }
        }
    }
 
    public boolean isComputerExist(Computer computer) {
        return findByName(computer.getName())!=null;
    }
 
    private static List<Computer> populateDummyComputers(){
        List<Computer> computers = new ArrayList<Computer>();
        computers.add(new Computer(counter.incrementAndGet(),"ThinkPad T450 20BVA02RCD","i7", 512,11999));
        computers.add(new Computer(counter.incrementAndGet(),"ALW17ER-4738","i7", 1537,23999));
        computers.add(new Computer(counter.incrementAndGet(),"GX700VO-ROG","i7", 512,45999));
        computers.add(new Computer(counter.incrementAndGet(),"Predator 17","i7", 1152,17599));
        return computers;
    }
 
    public void deleteAllComputers() {
       computers.clear();
    }

	
}
